clc;
clear all;
close all;

%% PARAMETERS
N = 3;%Number of hidden state values
M = 3;%Number of observations
T = 5;%Number of times/frames

P = zeros(N,1);%Initial state prob.
A = zeros(N, N);%State transition prob.
B = zeros(M, N);%Prob. of observation given state

P = [1/3 1/3 1/3];
A = [0.2 0.3 0.5;
     0.2 0.2 0.6;
     0   0.2 0.8];
 
 B(:,1) = [0.7 0.2 0.1]';%Given state 1 (Good Mood)
 B(:,2) = [0.3 0.4 0.3]';%Given state 2 (Neutral Mood)
 B(:,3) = [0.0 0.1 0.9]';%Given state 3 (Bad mood)
 O = [1 3 2 1 3];
 
 delta = zeros(N, T);
 psi = zeros(N, T);
 
 %Initialization
 for j = 1:N     
     od = O(1);
     delta(j,1) = P(j) * B(od, j);
     psi(j,1) = 0;
 end
 
 %Next state
 for t = 1:T-1
     for j = 1:N
         delta(j,t+1) = 0;
         psi(j,t+1) = 0;
         for i = 1:N
             ob_data = O(t+1);
             path = delta(i,t) * A(i,j) * B(ob_data,j);
             if path >= delta(j,t+1)
                 delta(j,t+1) = path;
                 psi(j,t+1) = i;
             end
         end
     end
 end
 
 %% PRINTING
clc;
disp('Result');
disp('DELTA');
fprintf('%1.4f \t%1.4f \t%1.4f \t%1.4f \t%1.4f\n', delta');
disp('PSI');
fprintf('%1.4f \t%1.4f \t%1.4f \t%1.4f \t%1.4f\n', psi');
